package com.tyc.threalpool;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionException;

public class TaskQueue extends LinkedBlockingDeque {
    public TaskQueue(int size){
        super(size);
    }

    private CustomThreadPoolExecutor threadPoolExecutor;

    public void setThreadPoolExecutor(CustomThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    @Override
    public boolean offer(Object o) {
        if (threadPoolExecutor == null) {
            throw new RejectedExecutionException("The task queue does not have executor!");
        }
        // 线程池的当前线程数
        int currentPoolThreadSize = threadPoolExecutor.getPoolSize();
        int submittedTaskCount = threadPoolExecutor.getSubmittedTaskCount();
        // 线程池中有空闲线程，直接扔进队列里，让线程去处理
        if(submittedTaskCount < currentPoolThreadSize){
            super.offer(o);
        }
        // 当前线程数小于 最大线程数 ，返回false，暗含入队失败，让线程池去创建新的线程
        if(currentPoolThreadSize < threadPoolExecutor.getMaximumPoolSize()){
            return false;
        }
        // 重点: 代码运行到此处，说明当前线程数 >= 最大线程数，需要真正的提交到队列中
        return super.offer(o);
    }

}
